package com.zhuoyian.dl.control;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;

import android.annotation.SuppressLint;

import com.zhuoyian.dl.service.DownloadPresent;
import com.zhuoyian.dl.util.ConnUtil;
import com.zhuoyian.dl.util.DownloadLog;
import com.zhuoyian.dl.util.DownloadThreadFactory;

/**
 * 串行下载
 * @author Administrator
 *
 */
public class SerialDownload  extends DownloadControl{
	private static DownloadControl serialDL;
	private LinkedList<DownloadPresent> dlData;
	private boolean isRun;

	/**
	 * ���ʵ��
	 */
	public static DownloadControl getInstance() {
		if (serialDL == null) {
			synchronized (SerialDownload.class) {
				if (serialDL == null) {
					serialDL = new SerialDownload();
				}
			}
		}
		return serialDL;
	}

	/**
	 * ����
	 */
	@SuppressLint("UseSparseArrays") 
	private SerialDownload() {
		super();
		dlData = new LinkedList<DownloadPresent>();
		isRun = false;
	}

	/**
	 * ��������
	 */
	@Override
	public int start(final DownloadPresent dlPresent) {
		super.start(dlPresent);
		if (isRun) {
			dlData.add(dlPresent);
		} else {
			DownloadThreadFactory.THREAD.submit(new Runnable() {

				@Override
				public void run() {
					executeTask(dlPresent);
				}
			});
		}
		return dlPresent.getTaskId();
	}

	private void executeTask(DownloadPresent dlPresent) {
		isRun = true;
		URL url = null;
		try {
			url = new URL(dlPresent.getDlFile().getUrl());
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		if (url == null) {
			return;
		}
		HttpURLConnection conn = ConnUtil.connect(url);
		if (conn == null) {
			DownloadLog.print("connection time out");
			execuNext();
			return;
		}
		int size = conn.getContentLength();
		conn.disconnect();
		conn = null;
		dlPresent.setFileSize(size);
		if (size <= 0) {
			execuNext();
			return;
		}
		dlPresent.download( url);
		execuNext();
	}

	private void execuNext() {
		if (isNext()) {
			DownloadThreadFactory.THREAD.submit(new Runnable() {

				@Override
				public void run() {
					executeTask(dlData.removeLast());
				}
			});
		} else {
			isRun = false;
		}
	}

	public synchronized boolean isNext() {
		return dlData.size() > 0;
	}
}
